const {Router} = require('express')
const router = new Router()

const path = require('path')

// 引入角色验证
const rolesPermission = require('../../../utils/validateRole/rolesPermission')
// 引入解析MarkerDown的模块
const marked = require('../../../config/marked')
// 引入商品信息模型
const GoodsInformationModel = require('../../../model/goodsInformation')
// 引入用户信息模型
const UserImformationModel = require('../../../model/userImformation')
// 引入地址模型
const AreaListModel = require('../../../model/areaList')
// 引入移动文件方法
const moveFile = require('../../../utils/fileUtils/moveFile')
// 引入url
const url = require('../../../config/url')


router.post('/updateGoods',function (request, response) {
    const {goodsId, hostId, oprate} = request.body

    const updateType = parseInt(request.body.updateType)
    // updateType = 0时表示当前是允许上架商品或者违规商品处理,所以该角色的权限必须是admin
    const examine = {
        code: '200',
        data: 'error',
        msg: '权限不足'
    }

    // 当前路由只能有后台权限的人员进入
    if(updateType == 0){
        const validate = {
            permitRoles: ['admin'],
            secret: request.get('permission')
        }
        if(!rolesPermission(validate)) return response.json(examine)

        const {isSell} = oprate

        examine.msg = '审核商品失败'
        GoodsInformationModel.findOneAndUpdate({
            _id: goodsId
        },{
            isShell
        },function (err,doc) {
            if(err) return response.json(examine)

            examine.data = 'success'
            examine.msg = '审核商品成功'

            return response.json(examine)
        })
    }else if (updateType == 1){
        const {address, addressCode} = oprate
        let addressTmp = null
        if (typeof(address) == 'object') addressTmp = address
        else addressTmp = addressCode
        // 先进行地址结果的检索，前后端使用的address是一样的，后面再考虑后端传入数据给前端
        AreaListModel.aggregate()
            .unwind('areaList')
            .unwind('areaList.areaList')
            .match({
                'code': addressTmp[0],
                'areaList.code': addressTmp[1],
                'areaList.areaList.code': addressTmp[2]
            })
            .exec(function (err,doc) {
                if (err) return console.log(err);

                let data = doc[0]
                addressSearchResult = `${data.name} ${data.areaList.name} ${data.areaList.areaList.name}`

                updateDoc(request, response, addressSearchResult)
            })


    }else {
       examine.data = '修改类型不合法'
       return response.json(examine)
    }

})

function updateDoc(request, response, addressSearchResult){
    const examine = {
        code: '200',
        data: 'error',
        msg: '权限不足'
    }

    const validate = {
        permitRoles: ['admin','boss','manager','server'],
        secret: request.get('permission')
    }
    if(!rolesPermission(validate)) return response.json(examine)

    const {oprate, goodsId, hostId} = request.body
    const { goodsName, goodsSecondTitle, goodsThumb, isSell, addressCode, searchFont, firstTitle, secondTitle, priceTable, pricePicArr, goodsDecMD, goodsDecPicArr } = oprate
    let goodsDec = marked ( goodsDecMD )

    let fileArr = [...goodsThumb, ...pricePicArr, ...goodsDecPicArr]
    let reg = new RegExp(url+'public/free/temp','g')
    fileArr = fileArr.map(value => {
        if (reg.test(value)) return value
    })

    let statusArr = []
    Promise.all(fileArr.map( tmpPath =>{
        if (tmpPath){
            const fileName = (path.parse(tmpPath)).base
            const newFilePath = path.resolve(__dirname,'../../../public/free/goodsPic',fileName)
            const oldFilePath = path.resolve(__dirname,'../../../public/free/temp',fileName)

            return new Promise((resolve, reject) => {
                moveFile(newFilePath, oldFilePath, status => {
                    if (!status.isSuccess) statusArr.push(status);

                    resolve(true)
                })
            })
        }
    })).then(res =>{
        const data = {
            code: '200',
            data: 'error',
            msg: '修改商品失败！'
        }

        UserImformationModel.findOne({
            _id: hostId
        },function (err, doc) {
            if (err) return response.json(data);

            if (doc.roles.indexOf('admin') != -1 || doc.roles.indexOf('boss') != -1){
                let reg = new RegExp( url+'public/free/temp','g')
                // 因为g是全局匹配，所以会把匹配到的所有内容都替换
                goodsDec = goodsDec.replace( reg, url+'public/free/goodsPic' )
                const MD = goodsDecMD.replace( reg, url+'public/free/goodsPic' )
                // 正则遍历再返回变更后的数组
                let newGoodsThumb = goodsThumb.map(item=>{
                    return item.replace( reg, url+'public/free/goodsPic' )
                })
                // 正则遍历再返回变更后的数组
                let newPriceTable = priceTable.map(item=>{
                    item.pricePic = item.pricePic.replace( reg, url+'public/free/goodsPic' )
                    return item
                })

                let sellType = 0
                if (parseInt(isSell) == 0) sellType = 3

                if(statusArr.length == 0){
                    // 商品修改
                    GoodsInformationModel.findOne({
                        _id: goodsId
                    },function (err,doc) {
                        if (err) return response.json(data)

                        doc.goodsName = goodsName
                        doc.goodsSecondTitle = goodsSecondTitle
                        doc.goodsThumb = newGoodsThumb
                        doc.isSell = sellType
                        doc.searchFont = searchFont
                        doc.addressCode = addressCode
                        doc.address = addressSearchResult
                        doc.firstTitle = firstTitle,
                        doc.secondTitle = secondTitle,
                        doc.priceTable = newPriceTable
                        doc.goodsDec = goodsDec
                        doc.goodsDecMD = MD
                        doc.hostId = hostId

                        doc.save(function (err,doc) {
                            if (err) return response.json(data)

                            data.data = 'success'
                            data.msg = '修改商品成功'

                            return response.json(data)
                        })
                    })
                }else {
                    statusArr.forEach(err=>{
                        console.log(err.err)
                    })
                    return response.json(data)
                }

            }else {
                data.msg = '用户权限不足'
                return response.json(data)
            }

        })
    })
}

module.exports =router
